/*
 * Copyright 2011 Katsunori Koyanagi
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package sweezy.swf.converter
{
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import sweezy.swf.structure.Matrix;
	import sweezy.swf.structure.Rect;

	public class GeomConverter
	{

		public static function matrixNativeToStructure(from:flash.geom.Matrix):sweezy.swf.structure.Matrix
		{
			if (from === null)
			{
				return null;
			}

			var to:sweezy.swf.structure.Matrix = new sweezy.swf.structure.Matrix();
			to.scaleX = from.a;
			to.rotateSkew0 = from.b;
			to.rotateSkew1 = from.c;
			to.scaleY = from.d;
			to.translateX = UnitConverter.pixelToTwip(from.tx);
			to.translateY = UnitConverter.pixelToTwip(from.ty);

			return to;
		}

		public static function matrixStructureToNative(from:sweezy.swf.structure.Matrix):flash.geom.Matrix
		{
			if (from === null)
			{
				return null;
			}

			var to:flash.geom.Matrix = new flash.geom.Matrix();
			to.a = isNaN(from.scaleX) ? 1 : from.scaleX;
			to.b = isNaN(from.rotateSkew0) ? 0 : from.rotateSkew0;
			to.c = isNaN(from.rotateSkew1) ? 0 : from.rotateSkew1;
			to.d = isNaN(from.scaleY) ? 1 : from.scaleY;
			to.tx = UnitConverter.twipToPixel(from.translateX);
			to.ty = UnitConverter.twipToPixel(from.translateY);

			return to;
		}

		public static function rectNativeToStructure(from:Rectangle):Rect
		{
			if (from === null)
			{
				return null;
			}

			var to:Rect = new Rect();
			to.xMin = UnitConverter.pixelToTwip(from.left);
			to.yMin = UnitConverter.pixelToTwip(from.top);
			to.xMax = UnitConverter.pixelToTwip(from.right);
			to.yMax = UnitConverter.pixelToTwip(from.bottom);

			return to;
		}

		public static function rectStructureToNative(from:Rect):Rectangle
		{
			if (from === null)
			{
				return null;
			}

			var to:Rectangle = new Rectangle();
			to.left = UnitConverter.twipToPixel(from.xMin);
			to.top = UnitConverter.twipToPixel(from.yMin);
			to.right = UnitConverter.twipToPixel(from.xMax);
			to.bottom = UnitConverter.twipToPixel(from.yMax);

			return to;
		}
	}
}
